package com.uwosh.cs342.g6.mapapp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Newfriend extends Activity {

	Context useThisForToast = this;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newfriend);
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);

		final EditText receiver = (EditText) findViewById(R.id.Friend2);

		findViewById(R.id.Add).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {

				EditText nameField = (EditText) findViewById(R.id.Friend2);

				String usernameToCheck = nameField.getText().toString();

				new checkUser().execute(usernameToCheck);

			}
		});
	}

	public void close() {
		this.finish();
	}
	
	public void listFriends(View v)
	{
		this.finish();
		Intent MainActivity = new Intent(this, FriendList.class);

	    startActivity(MainActivity);
	}

	public class checkUser extends AsyncTask<String, Void, Integer> {

		@Override
		protected Integer doInBackground(String... params) {

			HttpClient httpclient = new DefaultHttpClient();

			HttpPost httppost = new HttpPost(
					"http://softeng.cs.uwosh.edu/students/cs342g6/checkUser.php?username="
							+ params[0]);

			try {

				// Execute HTTP Post Request

				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String response = httpclient.execute(httppost, responseHandler);
				int intResponse = Integer.parseInt(response);

				if (intResponse >= 1) {
					return intResponse;
				} else {
					return -1;
				}

				// This is the response from a php application

			} catch (ClientProtocolException e) {
				// Toast.makeText(params[0], "CPE response " + e.toString(),
				// Toast.LENGTH_LONG).show();
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// Toast.makeText(params[0], "IOE response " + e.toString(),
				// Toast.LENGTH_LONG).show();
				// TODO Auto-generated catch block
			}
			return -1;

		} // end method doInBackground

		@Override
		protected void onPostExecute(Integer a) {
			if (a >= 1) {
				Toast.makeText(useThisForToast, "Success! User exists",
						Toast.LENGTH_SHORT).show();
				new SendFriendRequest().execute(Login.currentUserId, a);

			} else {
				Toast.makeText(useThisForToast, "Failure user doesn't exist",
						Toast.LENGTH_SHORT).show();
			}

		} // end method onPostExecute

	}

	public class SendFriendRequest extends AsyncTask<Integer, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Integer... params) {

			String urlText = "http://softeng.cs.uwosh.edu/students/cs342g6" +
					"/insertFriend.php?friendOne="
					+ params[0] + "&friendTwo=" + params[1];
			
			Log.d("PARAMS",""+params[0]+params[1]);

			HttpClient httpclient = new DefaultHttpClient();

			HttpPost httppost = new HttpPost(urlText);

			try {

				// Execute HTTP Post Request

				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String response = httpclient.execute(httppost, responseHandler);
				int intResponse = Integer.parseInt(response);

				if (Integer.parseInt(response) >= 1) {
					return true;
				} else {
					return false;
				}

				// This is the response from a php application

			} catch (ClientProtocolException e) {
				// Toast.makeText(params[0], "CPE response " + e.toString(),
				// Toast.LENGTH_LONG).show();
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// Toast.makeText(params[0], "IOE response " + e.toString(),
				// Toast.LENGTH_LONG).show();
				// TODO Auto-generated catch block
			}
			return false;

		} // end method doInBackground
		@Override
		protected void onPostExecute(Boolean a) {
			if (a == true) {
				Toast.makeText(useThisForToast, "Success! Request sent",
						Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(useThisForToast, "Failure! Request not sent",
						Toast.LENGTH_SHORT).show();
			}

		} // end method onPostExecute
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_newfriend, menu);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
